<template>
  <div class="task-list">
    <div class="task-header">
      <h2 class="page-title">万物迁移列表</h2>
      <el-button 
        type="primary" 
        :icon="Refresh" 
        @click="refreshTaskList"
        :loading="loading"
        class="refresh-btn"
      >
        刷新
      </el-button>
    </div>

    <!-- 任务列表 -->
    <div class="task-content">
      <div v-loading="loading" class="task-grid">
        <div 
          v-for="task in taskList" 
          :key="task.id" 
          class="task-card"
        >
          <!-- 预览图/视频区 -->
          <div class="card-image">
            <!-- 优先显示封面图，只要url有值就显示 -->
            <img 
              v-if="task.url" 
              :src="task.url" 
              class="preview-img"
              @click="task.status === 5 ? handleVideoPreview(task) : previewImage(task.url)"
            />
            <!-- 如果没有url，显示默认状态 -->
            <div v-else class="default-image">
              <el-icon class="default-icon"><Picture /></el-icon>
              <span class="default-text">生成中...</span>
            </div>
            
            <!-- 视频播放按钮覆盖层 -->
            <div v-if="task.status === 5 && task.url" class="video-play-overlay" @click="handleVideoPreview(task)">
              <div class="play-button">
                <el-icon class="play-icon"><VideoPlay /></el-icon>
              </div>
            </div>
            
            <!-- 状态提示覆盖层 -->
            <template v-if="task.status === 3 && task.url">
              <div 
                class="status-overlay"
                @click="goToImageToVideo(task)"
              >
                <div class="status-content">
                  <div class="status-icon">📹</div>
                  <div class="status-text">图片生成完成</div>
                  <div class="status-subtext">点击继续生成视频</div>
                </div>
              </div>
            </template>
          </div>
          
          <!-- 卡片内容 -->
          <div class="card-content">
            <div class="card-header">
              <div class="task-id">任务 #{{ task.id }}</div>
              <el-tag 
                :type="getStatusType(task.status)"
                :effect="task.status === 1 ? 'plain' : 'dark'"
                size="small"
              >
                {{ getStatusText(task.status) }}
              </el-tag>
            </div>
            
            <div class="card-info">
              <div class="info-item create-time">
                <span class="label">创建时间:</span>
                <span class="value">{{ task.create_time }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 图片预览弹窗 -->
    <el-dialog v-model="showPreview" title="图片预览" width="80%" class="preview-dialog">
      <div class="preview-container">
        <img :src="previewImageUrl" class="preview-large-img" />
      </div>
    </el-dialog>

    <!-- 视频预览弹窗 -->
    <el-dialog v-model="showVideoDialog" title="视频预览" width="600px" @close="previewVideoUrl = ''">
      <div v-if="previewVideoUrl">
        <video :src="previewVideoUrl" controls style="width:100%;border-radius:8px;" />
        <div style="margin-top:16px;text-align:center;">
          <el-button type="primary" @click="downloadVideo">下载视频</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, VideoPlay, Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { API_CONFIG, apiRequest } from '../../config/api.js'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const taskList = ref([])
const showPreview = ref(false)
const previewImageUrl = ref('')
const showVideoDialog = ref(false)
const previewVideoUrl = ref('')

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 获取任务列表
async function getTaskList() {
  loading.value = true
  try {
    const params = new URLSearchParams({
      page: String(pagination.page),
      pageSize: String(pagination.pageSize)
    })

    const response = await apiRequest(`/productAnyShoot/task/list?${params.toString()}`, {
      method: 'GET'
    })

    if (response.code === 200) {
      taskList.value = response.data.list
      console.log('任务列表:', taskList.value.map(task => ({
        id: task.id,
        status: task.status,
        url: task.url,
        hasImages: task.result_images && task.result_images.length > 0
      })))
      pagination.total = response.data.total
      pagination.page = response.data.page
      pagination.pageSize = response.data.pageSize
    } else {
      throw new Error(response.msg || '获取任务列表失败')
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error(error.message || '获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 获取状态类型
function getStatusType(status) {
  switch (status) {
    case 0: return 'info'     // 待处理
    case 1: return 'warning'  // 图片生成中
    case 2: return 'danger'   // 图片生成失败
    case 3: return 'info'     // 等待图转视频
    case 4: return 'warning'  // 图转视频中
    case 5: return 'success'  // 图转视频成功
    case 6: return 'danger'   // 图转视频失败
    default: return 'info'
  }
}

// 获取状态文本
function getStatusText(status) {
  switch (status) {
    case 0: return '待处理'
    case 1: return '图片生成中'
    case 2: return '图片生成失败'
    case 3: return '等待图转视频'
    case 4: return '图转视频中'
    case 5: return '图转视频成功'
    case 6: return '图转视频失败'
    default: return '未知状态'
  }
}

// 分页处理
function handleSizeChange(size) {
  pagination.pageSize = size
  pagination.page = 1
  getTaskList()
}

function handleCurrentChange(page) {
  pagination.page = page
  getTaskList()
}

// 预览图片
function previewImage(url) {
  previewImageUrl.value = url
  showPreview.value = true
}

// 下载图片
async function downloadImages(task) {
  if (!task.url) {
    ElMessage.warning('该任务没有可下载的图片')
    return
  }

  try {
    const link = document.createElement('a')
    link.href = task.url
    link.download = `task_${task.task_id}_result.jpg`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('图片下载已开始')
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

// 重试任务
async function retryTask(task) {
  try {
    await ElMessageBox.confirm('确定要重试这个任务吗？', '确认重试', {
      type: 'warning'
    })

    const response = await apiRequest(`/productAnyShoot/task/retry/${task.id}`, {
      method: 'POST'
    })

    if (response.code === 200) {
      ElMessage.success('任务重试成功')
      getTaskList()
    } else {
      throw new Error(response.msg || '重试失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '重试失败')
    }
  }
}

// 跳转到图转视频页面
function goToImageToVideo(task) {
  if (!task.url) {
    ElMessage.warning('该任务没有可用的图片')
    return
  }
  // 只encode一次
  let encodedUrl = task.url
  try {
    if (decodeURIComponent(task.url) === task.url) {
      encodedUrl = encodeURIComponent(task.url)
    }
  } catch (e) {}
  router.push({
    path: '/imageToVideo',
    query: {
      image: encodedUrl,
      taskId: task.id,
      key: task.key
    }
  })
}

function handleVideoPreview(task) {
  if (task.status !== 5) return
  let filePath = ''
  try {
    const arr = JSON.parse(task.result_videos)
    if (arr && arr.length > 0 && arr[0].originVideo && arr[0].originVideo.filePath) {
      filePath = arr[0].originVideo.filePath
    }
  } catch (e) {}
  if (filePath) {
    previewVideoUrl.value = filePath
    showVideoDialog.value = true
  }
}

function downloadVideo() {
  if (!previewVideoUrl.value) return
  const link = document.createElement('a')
  link.href = previewVideoUrl.value
  link.download = 'result_video.mp4'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 刷新任务列表
function refreshTaskList() {
  getTaskList()
}

// 组件挂载时获取数据
onMounted(() => {
  getTaskList()
})
</script>

<style scoped>
.task-list {
  padding: 24px;
  background: #18181c;
  min-height: 100vh;
  color: #fff;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #fff;
}

.refresh-btn {
  background: linear-gradient(135deg, #409eff, #66b1ff) !important;
  border: none !important;
  color: #fff !important;
  font-weight: 600 !important;
  padding: 10px 20px !important;
  border-radius: 8px !important;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3) !important;
  transition: all 0.3s ease !important;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #66b1ff, #409eff) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4) !important;
}

.refresh-btn:active {
  transform: translateY(0) !important;
}

.task-content {
  background: #23232a;
  border-radius: 12px;
  padding: 20px;
}

.task-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.task-card {
  background: #2a2a2a;
  border-radius: 12px;
  padding: 0;
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid #333;
}

.task-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
  border-color: #409eff;
}

.card-image {
  position: relative;
  width: 100%;
  height: 200px;
  background: #333;
  overflow: hidden;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  display: block;
  transition: transform 0.3s ease;
}

.preview-img:hover {
  transform: scale(1.05);
}

.default-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.default-icon {
  font-size: 32px;
  color: #666;
  margin-bottom: 8px;
}

.default-text {
  font-size: 14px;
  color: #888;
}

.card-content {
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.task-id {
  font-size: 16px;
  font-weight: 600;
  color: #fff;
}

.card-info {
  display: flex;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item.create-time {
  flex: 1;
  min-width: 0;
}

.label {
  font-size: 12px;
  color: #888;
}

.value {
  font-size: 14px;
  font-weight: 500;
  color: #fff;
}

.card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.card-actions .el-button {
  font-size: 12px;
  padding: 6px 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .task-grid {
    grid-template-columns: 1fr;
  }
  
  .card-actions {
    justify-content: center;
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-large-img {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

/* 暗色主题样式 */
:deep(.el-pagination) {
  color: #fff !important;
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-pagination .el-pager li) {
  background: #333 !important;
  color: #fff !important;
  border: 1px solid #444 !important;
  border-radius: 4px !important;
  margin: 0 2px !important;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: #409eff !important;
  color: #fff !important;
}

:deep(.el-pagination button) {
  background: #333 !important;
  color: #fff !important;
  border: 1px solid #444 !important;
  border-radius: 4px !important;
  margin: 0 2px !important;
}

:deep(.el-pagination button:hover) {
  background: #444 !important;
  border-color: #555 !important;
}

:deep(.el-pagination button:disabled) {
  background: #222 !important;
  color: #666 !important;
  border-color: #333 !important;
}

/* 每页数量选择器样式覆盖 - 去掉白边 */
:deep(.el-pagination .el-select) {
  background: #23232a !important;
  border: none !important;
  border-radius: 4px !important;
}

:deep(.el-pagination .el-select .el-input) {
  background: #23232a !important;
  border: none !important;
}

:deep(.el-pagination .el-select .el-input__wrapper) {
  background: #23232a !important;
  box-shadow: none !important;
  border: none !important;
  border-radius: 4px !important;
}

:deep(.el-pagination .el-select .el-input__inner) {
  background: #23232a !important;
  color: #909399 !important;
  border: none !important;
  padding: 0 8px !important;
}

:deep(.el-pagination .el-select .el-select__caret) {
  color: #909399 !important;
}

/* 针对每页数量选择的下拉框 - 去掉白边 */
:deep(.el-pagination__sizes .el-select) {
  background: #23232a !important;
  border: none !important;
  border-radius: 4px !important;
}

:deep(.el-pagination__sizes .el-select .el-input__wrapper) {
  background: #23232a !important;
  box-shadow: none !important;
  border: none !important;
  border-radius: 4px !important;
}

:deep(.el-pagination__sizes .el-select .el-input__inner) {
  background: #23232a !important;
  color: #909399 !important;
  border: none !important;
  padding: 0 8px !important;
}

/* 专门针对每页数量选择器 - 去掉白边 */
:deep(.el-pagination__sizes) {
  background: transparent !important;
}

:deep(.el-pagination__sizes .el-select .el-input) {
  background: #23232a !important;
  border: none !important;
  border-radius: 4px !important;
}

:deep(.el-pagination__sizes .el-select .el-input:focus) {
  border: none !important;
  box-shadow: none !important;
}

/* 下拉选项样式 */
:deep(.el-select-dropdown) {
  background: #23232a !important;
  border: 1px solid #333 !important;
}

:deep(.el-select-dropdown__item) {
  color: #909399 !important;
}

:deep(.el-select-dropdown__item.hover) {
  background: #2a2a2a !important;
}

:deep(.el-select-dropdown__item.selected) {
  background: #2a2a2a !important;
  color: #409eff !important;
}

/* 强制覆盖所有分页组件内的选择器背景 - 去掉白边 */
:deep(.pagination-wrapper .el-select),
:deep(.pagination-wrapper .el-select *),
:deep(.el-pagination .el-select),
:deep(.el-pagination .el-select *) {
  background: #23232a !important;
  background-color: #23232a !important;
  color: #909399 !important;
  border: none !important;
  border-color: transparent !important;
}

/* 专门针对每页数量选择器的所有状态 - 去掉白边 */
:deep(.el-pagination__sizes .el-select:hover),
:deep(.el-pagination__sizes .el-select:focus),
:deep(.el-pagination__sizes .el-select:active) {
  background: #23232a !important;
  border: none !important;
}

:deep(.el-pagination__sizes .el-select .el-input:hover),
:deep(.el-pagination__sizes .el-select .el-input:focus),
:deep(.el-pagination__sizes .el-select .el-input:active) {
  background: #23232a !important;
  border: none !important;
}

/* 强制覆盖所有输入框背景 */
:deep(.pagination-wrapper .el-input),
:deep(.pagination-wrapper .el-input *),
:deep(.el-pagination .el-input),
:deep(.el-pagination .el-input *) {
  background: #23232a !important;
  background-color: #23232a !important;
  color: #909399 !important;
}

/* 最强力覆盖 - 包括所有状态 */
:deep(.el-pagination) input,
:deep(.el-pagination) input:focus,
:deep(.el-pagination) input:hover,
:deep(.el-pagination) .el-input__inner,
:deep(.el-pagination) .el-input__wrapper,
:deep(.el-pagination) .el-select,
:deep(.el-pagination) .el-select .el-input,
:deep(.el-pagination) .el-select .el-input__inner,
:deep(.el-pagination) .el-select .el-input__wrapper {
  background: #23232a !important;
  background-color: #23232a !important;
  color: #909399 !important;
  border: 1px solid #333 !important;
  border-color: #333 !important;
  box-shadow: none !important;
  outline: none !important;
}

/* 确保所有分页元素都没有白边 */
:deep(.el-pagination *),
:deep(.el-pagination *:before),
:deep(.el-pagination *:after) {
  background-color: transparent !important;
  border-color: #333 !important;
}

/* 分页容器背景 */
:deep(.el-pagination) {
  background: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
}

/* 分页文本颜色 */
:deep(.el-pagination .el-pagination__total),
:deep(.el-pagination .el-pagination__jump) {
  color: #909399 !important;
}

.status-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 1;
}

.status-overlay:hover {
  background: rgba(0, 0, 0, 0.8);
}

.status-content {
  text-align: center;
  padding: 20px;
  color: #fff;
}

.status-icon {
  font-size: 40px;
  margin-bottom: 12px;
}

.status-text {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #fff;
}

.status-subtext {
  font-size: 14px;
  color: #ccc;
}

/* 视频播放按钮覆盖层 */
.video-play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 2;
}

.video-play-overlay:hover {
  background: rgba(0, 0, 0, 0.5);
}

.play-button {
  width: 60px;
  height: 60px;
  background: rgba(64, 158, 255, 0.9);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease;
  border: 3px solid #fff;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
}

.video-play-overlay:hover .play-button {
  background: rgba(64, 158, 255, 1);
  transform: scale(1.1);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
}

.play-icon {
  font-size: 24px;
  color: #fff;
  margin-left: 3px; /* 微调播放图标位置 */
}

.image-url {
  margin-top: 16px;
  margin-bottom: 16px;
}

.url-label {
  font-size: 12px;
  color: #888;
  margin-bottom: 8px;
}

.url-input {
  width: 100%;
}

:deep(.preview-dialog .el-dialog) {
  background: #23232a !important;
}
</style> 